<template>
  <div class="home">
    <mbx name1="商品管理" name2="参数列表" />
    <!-- card -->
    <el-card class="mt16">
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        effect="dark"
      >
      </el-alert>
      <!-- 选择商品分类 -->
      <el-row class="mt16">
        <el-col :span="3">选择商品分类：</el-col>
        <el-col :span="8">
          <el-cascader
            v-model="catarr"
            :options="options"
            :props="{
              expandTrigger: 'hover',
              value: 'cat_id',
              label: 'cat_name',
              children: 'children',
            }"
            @change="getParamsData()"
          ></el-cascader
        ></el-col>
      </el-row>
      <!-- 卡片式 -->
      <el-tabs
        v-model="activeName"
        type="border-card"
        class="mt16"
        @tab-click="handleClick"
      >
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加按钮部分 -->
          <el-row>
            <el-col :span="8">
              <el-button
                type="primary"
                :disabled="cd"
                @click="dialogFormVisible = true"
                >添加参数</el-button
              >
            </el-col>
          </el-row>
          <!-- 表格区 -->
          <el-table :data="dong" border style="width: 100%" class="mt16">
            <el-table-column fixed width="50" type="expand">
              <template #default="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  class="mx-1"
                  :disable-transitions="false"
                  @close="handleClose(scope.row, index)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="InputRef"
                  size="small"
                  @keyup.enter="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  class="el-icon-edit"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="del(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <!-- 添加按钮部分 -->
          <el-row>
            <el-col :span="8">
              <el-button
                type="primary"
                :disabled="cd"
                @click="dialogFormVisible = true"
                >添加参数</el-button
              >
            </el-col>
          </el-row>
          <!-- 表格区 -->
          <el-table :data="jing" border style="width: 100%" class="mt16">
            <el-table-column fixed width="50" type="expand">
              <template #default="scope">
                <el-tag
                  :key="index"
                  v-for="(item, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  class="mx-1"
                  @close="handleClose(scope.row, index)"
                >
                  {{ item }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="InputRef"
                  size="small"
                  @keyup.enter="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag ml-1"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  class="el-icon-edit"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="del(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加的模态框 -->
      <el-dialog title="添加动态参数" v-model="dialogFormVisible" @close="qk">
        <el-form
          :model="form"
          :rules="rules"
          ref="addref"
          class="demo-ruleForm"
        >
          <el-form-item label="添加动态参数" prop="attr_name">
            <el-input v-model="form.attr_name" style="width: 350px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="add">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑 -->
      <el-dialog title="修改动态参数" v-model="dialogFormVisible1" @close="qk">
        <el-form
          :model="form1"
          :rules="rules"
          ref="editadd"
          class="demo-ruleForm"
        >
          <el-form-item label="添加动态参数" prop="attr_name">
            <el-input v-model="form1.attr_name" style="width: 350px"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="xg">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, computed } from "vue";
import {
  getcate,
  getcanshulist,
  addtag,
  adddjlist,
  deltag,
} from "../http/api.js";
import { ElMessage, ElMessageBox } from "element-plus";
export default {
  setup(props) {
    const addref = ref(null);
    const editadd = ref(null);
    const inputValue = ref("");
    const InputRef = ref(null);
    const obj = reactive({
      activeName: "many",
      options: [],
      form: {
        attr_name: "",
        attr_sel: [],
        id: 0,
      },
      form1: {
        attr_name: "",
        attr_sel: [],
        id: 0,
      },
      catarr: [],
      dong: [],
      jing: [],
      inputVisible: false, //控制input框显示
      inputValue: "",
      dialogFormVisible: false,
      dialogFormVisible1: false,
      rules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },
    });
    // 挂载
    onMounted(() => {
      getlist();
    });
    // 渲染数据
    const getlist = async () => {
      const res = await getcate();
      console.log("分类参数数据", res);
      obj.options = res;
    };
    // 渲染动态或静态数据
    const getParamsData = async () => {
      if (obj.catarr.length !== 3) {
        ElMessage.error("必须选择三级的才可以呦!");
        obj.dong = [];
        obj.jing = [];
        return false;
      }
      // 根据所选分类的id,和在当前所处的面板,获取数据
      const res = await getcanshulist(
        obj.catarr[obj.catarr.length - 1],
        obj.activeName
      );
      res.forEach((item) => {
        item.inputVisible = false;
        item.inputValue = "";
        item.attr_vals =
          item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
      });
      console.log("参数列表1", res);
      if (obj.activeName == "many") {
        obj.dong = res;
      } else if (obj.activeName == "only") {
        obj.jing = res;
      }
      console.log("动态", obj.dong);
      console.log("静态", obj.jing);
    };
    const cd = computed(() => {
      return obj.catarr.length !== 3;
    });
    // tab栏切换
    const handleClick = () => {
      getParamsData();
    };
    // 失去焦点时
    const handleInputConfirm = async (row) => {
      if (row.inputValue.trim().length > 0) {
        row.attr_vals.push(row.inputValue);
        await addtag(obj.catarr[obj.catarr.length - 1], row.attr_id, {
          attr_name: row.attr_name,
          attr_sel: obj.activeName,
          attr_vals: row.attr_vals.join(","),
        });
      }
      row.inputVisible = false;
      row.inputValue = "";
    };
    // input框打开
    const showInput = (row) => {
      row.inputVisible = true;
      // nextTick(() => {InputRef.value!.input!.focus()})
    };
    // 删除当前行参数
    const del = (row) => {
      ElMessageBox.confirm("您确定要删除它吗?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        .then(async () => {
          const res = await deltag(
            obj.catarr[obj.catarr.length - 1],
            row.attr_id
          );
          console.log("删除", res);
          getParamsData();
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    // 删除某一行
    const handleClose = (row, index) => {
      ElMessageBox.confirm("您确定要删除它吗?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        type: "warning",
      })
        .then(async () => {
          row.attr_vals.splice(index, 1);
          await addtag(obj.catarr[obj.catarr.length - 1], row.attr_id, {
            attr_name: row.attr_name,
            attr_sel: obj.activeName,
            attr_vals: row.attr_vals.join(","),
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "Delete canceled",
          });
        });
    };
    // 添加动态参数
    const add = () => {
      obj.form.id = obj.catarr[obj.catarr.length - 1];
      obj.form.attr_sel = obj.activeName;
      addref.value.validate(async (valid) => {
        if (valid) {
          const res = await adddjlist(obj.form);
          console.log("用户的数据", res);
          obj.form.attr_name = "";
          obj.dialogFormVisible = false;
          getParamsData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    // 清空
    const qk = () => {
      obj.form.attr_name = "";
    };
    // 动态编辑
    const edit = (row) => {
      obj.dialogFormVisible1 = true;
      obj.form1.attr_name = row.attr_name;
      obj.form1.id = obj.catarr[obj.catarr.length - 1];
      obj.form1.attr_sel = obj.activeName;
      obj.form1.attr_id = row.attr_id;
      obj.form1.attr_vals = row.attr_vals.join(",");
    };
    const xg = () => {
      editadd.value.validate(async (valid) => {
        if (valid) {
          const res = await addtag(
            obj.catarr[obj.catarr.length - 1],
            obj.form1.attr_id,
            {
              attr_name: obj.form1.attr_name,
              attr_sel: obj.activeName,
              attr_vals: obj.form1.attr_vals,
            }
          );
          console.log("用户的数据", res);
          obj.form.attr_name = "";
          obj.dialogFormVisible1 = false;
          getParamsData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };
    return {
      ...toRefs(obj),
      handleInputConfirm,
      showInput,
      del,
      handleClose,
      addref,
      qk,
      editadd,
      getParamsData,
      cd,
      edit,
      xg,
      add,
    };
  },
};
</script>

<style lang="scss" scoped>
.home {
  width: 100%;
  .h {
    width: 100%;
    display: flex;
  }
  .el-tag {
    margin: 6px 10px;
  }
  .el-input {
    width: 100px;
  }
}
</style>
